package com.yy.strategy.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.yy.constant.AuthConstant;
import com.yy.domain.LoginSysUser;
import com.yy.mapper.LoginSysUserMapper;
import com.yy.model.SecurityUser;
import com.yy.strategy.LoginStrategy;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;

import java.util.Set;

@Component(value = AuthConstant.SYS_USER_LOGIN)
@Log4j2
public class SysUserLoginStrategy implements LoginStrategy {
    @Autowired
    private LoginSysUserMapper loginSysUserMapper;

    @Override
    public UserDetails realLogin(String username) {
        LoginSysUser loginSysUser = loginSysUserMapper.selectOne(new LambdaQueryWrapper<LoginSysUser>()
                .eq(LoginSysUser::getUsername, username));
        if (ObjectUtils.isEmpty(loginSysUser)) {
            throw new UsernameNotFoundException("用户不存在");
        }
        //根据用户ID查询用户权限
        Set<String> perms = loginSysUserMapper.selectPermsBySysUserId(loginSysUser.getUserId());
        //创建一个返回对象
        SecurityUser securityUser = new SecurityUser();
        //把loginSysUser值copy到securityUser
        BeanUtils.copyProperties(loginSysUser, securityUser);
        //把登录类型放进去
        securityUser.setLoginType(AuthConstant.SYS_USER_LOGIN); //登录类型，因为会员和用户处理不同的表。可以ID一样，用类型去区分一下
        //把权限放入
        securityUser.setPerms(perms);
        return securityUser;
    }


}
